package com.farm.filter;


import com.farm.common.BaseContext;
import com.farm.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@Component
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的url
        String requestURI = request.getRequestURI();
        log.info("本次拦截:{}",requestURI);

        String[] urls = new String[]{
                "/user/user/login",

        };

        //判断路径匹配
        boolean check = check(urls, requestURI);

        //如果不需要处理
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        try {
            //获取 header里的token
            String token = (String) request.getHeader("token");
            log.info(token);
            Claims body = AppJwtUtil.getJws(token).getBody();
            Object username = body.get("username");
            Long id = Long.valueOf(((Integer)body.get("id")).toString());
            //判断是否登录了
            if(username != null){
                BaseContext.setCurrentId(id);
                filterChain.doFilter(request,response);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("JWT Token解析失败", e);
            // 处理解析失败的情况，可以返回特定的响应，如 401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("JWT Token解析失败");
            return;
        }

//        Claims body = AppJwtUtil.getJws(token).getBody();
//        Object username = body.get("username");
//        Long id = Long.valueOf(((Integer)body.get("id")).toString());
//        //判断是否登录了
//        if(username != null){
//            BaseContext.setCurrentId(id);
//            filterChain.doFilter(request,response);
//            return;
//        }

//        if(request.getSession().getAttribute("employee")!= null ){
//
//            Long empId = (Long) request.getSession().getAttribute("employee");
//            BaseContext.setCurrentId(empId);
//
//            filterChain.doFilter(request,response);
//            return;
//        }
//        if(request.getSession().getAttribute("user")!= null ){
//
//            Long userId = (Long) request.getSession().getAttribute("user");
//            BaseContext.setCurrentId(userId);
//
//            filterChain.doFilter(request,response);
//            return;
//        }

        //如果未登录,通过输出流
        //response.getWriter().write(JSON.toJSONString(ResponseResult.okResult("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配方法
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for(String url : urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return match;
            }
        }
        return false;
    }
}
